<template>
  <div>
    <el-card header="用户管理">
      <MForm :fields="fields" @submit="search" @cancel="search"> </MForm>
      <MTable
        :columns="columns"
        :http="userList"
        :params="params"
        v-model:isReload="isReload"
        v-model:selectKeys="selectKeys"
        height="calc(100vh - 450px)"
      >
        <template #extra>
          <el-button type="primary" @click="edit(0)">新增</el-button>
          <MDeleteButton
            :selectKeys="selectKeys"
            @click="del(selectKeys)"
          ></MDeleteButton>
        </template>

        <template #createAt="{ value }">
          <span v-dateFormat:YYYY-MM-DD="value"></span>
        </template>

        <template #actions="{ row }">
          <MA type="primary" @click="resetPassword(row.id)">重置密码</MA>
          <MA type="primary" @click="edit(row.id)">编辑</MA>
          <MA type="danger" @click="del([row.id])">删除</MA>
        </template>
      </MTable>
    </el-card>

    <MFormDialog
      v-model="formDialog.visible"
      v-bind="formDialog"
      :fields="dialogFields"
      :httpAdd="userAdd"
      :httpEdit="userEdit"
      :httpGet="userDetail"
      :getHandler="getHandler"
      @reload="reload"
    ></MFormDialog>
    <Popup ref="PopupRef" @reload="reload" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { columns, fields, dialogFields } from './config'
import {
  userList,
  userAdd,
  userEdit,
  userDetail,
  userDel
} from '@/api/system/user/user.ts'
import { roleSelect } from '@/api/system/role/role.ts'
import { areaList } from '@/api/system/organization/organization.ts'
import Popup from './popup/popup.vue'

onMounted(() => {
  roleSelect().then((res) => {
    dialogFields.forEach((item: any) => {
      if (item.key === 'role_ids') {
        item.attrs.options = res.map((i: any) => ({
          label: i.name,
          value: i.id
        }))
      }
    })
  })
  areaList().then((res) => {
    dialogFields.forEach((item: any) => {
      if (item.key === 'area_id') {
        item.attrs.data = res
      }
    })
  })
})

const PopupRef = ref()
const resetPassword = (id: number) => {
  PopupRef.value.show(id)
}

const getHandler = (data: any) => {
  data.role_ids = data?.roles?.map((i: any) => i.id)
  return data
}

// 搜索
const params = ref<any>({})
const search = (data: any) => {
  params.value = {
    ...params.value,
    ...data
  }
}

// 新增/编辑
const formDialog = reactive({
  visible: false,
  id: 0
})
const edit = (id: number) => {
  formDialog.id = id
  formDialog.visible = true
}

// 重载
const isReload = ref(true)
const reload = () => {
  isReload.value = true
}

const selectKeys = ref<number[]>([])
// 删除
const del = (ids: number[]) => {
  userDel({ ids }).then(() => {
    ElMessage.success('删除成功')
    reload()
  })
}
</script>

<style lang="scss" scoped></style>
